import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import Taro, {useDidShow} from '@tarojs/taro';
import {View, Text, Image} from '@tarojs/components';
import {AtForm, AtInput, AtButton} from 'taro-ui';
import { Input } from '@nutui/nutui-react-taro'
import getBaseUrl from "../../../service/baseUrl";
import './add.less';
import LicensePlateKeyboard from '../../../components/LicensePlateKeyboard';
import defaultVehicleLicense from '../../../assets/license.png';


const base = getBaseUrl();

function AddStation(props) {
    const {dispatch, myCar = {}} = props;
    const [carNum, setCarNum] = useState('');
    const [vin, setVin] = useState('');
    const [showKeyboard, setShowKeyboard] = useState(false);
    const [vehicleInfo, setVehicleInfo] = useState({
        plateNumber: '',
        vin: '',
        model: '',
        registerDate: '',
        owner: '',
        address: '',
        engineNo: '',
        useCharacter: '',
    });
    const [licenseImage, setLicenseImage] = useState('');

    useDidShow(() => {
        if (myCar && myCar.carNumber) {
            setCarNum(myCar.carNumber);
            setVin(myCar.vin);
        }
    });

    // 上传并识别行驶证
    const handleUploadLicense = async () => {
        try {
            // 选择图片
            const res = await Taro.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera']
            });

            if (res.tempFilePaths && res.tempFilePaths[0]) {
                setLicenseImage(res.tempFilePaths[0]);

                // 显示加载提示
                Taro.showLoading({
                    title: '识别中...'
                });

                // 构建FormData并上传
                try {
                    const uploadRes = await Taro.uploadFile({
                        // url: 'YOUR_API_ENDPOINT/recognize-license', // 替换为您的实际接口地址
                        url: `${base}/ocr/vehicleLicenseOCR`, // 替换为您的实际接口地址
                        filePath: res.tempFilePaths[0],
                        name: 'file', // 服务端接收文件的字段名
                        formData: {
                            'type': 'driving_license',
                            'timestamp': new Date().getTime()
                        },
                        header: {
                            'Content-Type': 'multipart/form-data',
                            // 如果需要认证token
                            'Authorization': "Bearer " + Taro.getStorageSync('access_token')
                        }
                    });
                    console.log('uploadRes', uploadRes);
                    // 解析响应数据
                    const result = JSON.parse(uploadRes.data);
                    console.log('uploadResresult', result);
                    if (result.code && result.code === 200) {
                        const licenseInfo = result.data;
                        if (licenseInfo.vin) {
                            setVehicleInfo({
                                plateNumber: licenseInfo.plate_num || '',
                                vin: licenseInfo.vin || '',
                                model: licenseInfo.model || '',
                                vehicle_type: licenseInfo.vehicle_type || '',
                                registerDate: licenseInfo.register_date || '',
                                owner: licenseInfo.owner || '',
                                address: licenseInfo.addr || '',
                                engineNo: licenseInfo.engine_num || '',
                                useCharacter: licenseInfo.use_character || ''
                            });

                            setCarNum(licenseInfo.plate_num || '');
                            setVin(licenseInfo.vin || '');

                            Taro.hideLoading();
                            Taro.showToast({
                                title: '识别成功',
                                icon: 'success'
                            });
                        } else {
                            throw new Error('您上传的不是行驶证,请重新上传');
                        }
                    } else {
                        throw new Error(result.message || '识别失败');
                    }
                } catch (uploadError) {
                    console.error('识别失败:', uploadError);
                    Taro.hideLoading();
                    Taro.showToast({
                        title: uploadError.message || '识别失败',
                        icon: 'none'
                    });
                }
            }
        } catch (error) {
            console.error('选择图片失败:', error);
            Taro.hideLoading();
            Taro.showToast({
                title: '选择图片失败',
                icon: 'none'
            });
        }
    };

    return (
        <View className='addWrap' onClick={() => setShowKeyboard(false)}>
            <View className='formWrap'>
                {/* 行驶证上传区域 */}
                <View className='license-upload' onClick={handleUploadLicense}>
                    <Image
                        className='license-image'
                        src={licenseImage || defaultVehicleLicense}
                        mode='aspectFit'
                    />
                    <Text className='upload-tip'>
                        {licenseImage ? '点击重新上传' : '点击上传行驶证'}
                    </Text>
                </View>

                <AtForm
                    onSubmit={() => {
                        if (carNum) {
                            dispatch({
                                type: myCar && myCar.carNumber ? 'cars/editCar' : 'cars/addCar',
                                payload: {
                                    ...vehicleInfo,
                                    carNumber: carNum,
                                    vin,
                                }
                            })
                        } else {
                            Taro.showToast({
                                title: '请完善必填信息再提交',
                                icon: 'none',
                                duration: 1500
                            })
                        }
                    }}
                >
                    <View className='input-item' onClick={(e) => {e.stopPropagation(); setShowKeyboard(true)}}>
                        <Text className='label'>车牌号</Text>
                        <Text className={`value ${!carNum && 'placeholder'}`}>
                            {carNum || '必填'}
                        </Text>
                    </View>

                  <View className='input-item'>
                    <Text className='label'>VIN码</Text>
                    <View className={`value ${!vin && 'placeholder'}`}>
                      <Input
                        placeholder='车辆识别代号'
                        value={vin}
                        onChange={(e) => setVin(e)}
                        style={{paddingRight: 0, textAlign: 'end', fontSize: '32rpx'}}
                      />
                    </View>
                    {/*<Text className={`value ${!carNum && 'placeholder'}`}>*/}
                    {/*  {carNum || '必填'}*/}
                    {/*</Text>*/}
                  </View>

                    <AtInput
                        name='model'
                        title='品牌型号'
                        type='text'
                        disabled
                        value={vehicleInfo.model}
                        onChange={(val) => setVehicleInfo(prev => ({...prev, model: val}))}
                    />
                    <AtInput
                        name='vehicle_type'
                        title='车辆类型'
                        type='text'
                        disabled
                        value={vehicleInfo.vehicle_type}
                        onChange={(val) => setVehicleInfo(prev => ({...prev, vehicle_type: val}))}
                    />
                    <AtInput
                        name='registerDate'
                        title='注册日期'
                        type='text'
                        disabled
                        value={vehicleInfo.registerDate}
                        onChange={(val) => setVehicleInfo(prev => ({...prev, registerDate: val}))}
                    />

                    <AtInput
                        name='owner'
                        title='所有人'
                        type='text'
                        disabled
                        value={vehicleInfo.owner}
                        onChange={(val) => setVehicleInfo(prev => ({...prev, owner: val}))}
                    />

                    <AtInput
                        name='engineNo'
                        title='发动机号'
                        type='text'
                        disabled
                        value={vehicleInfo.engineNo}
                        onChange={(val) => setVehicleInfo(prev => ({...prev, engineNo: val}))}
                    />

                    <AtButton formType='submit'>保存</AtButton>
                </AtForm>
            </View>
            {showKeyboard && (
                <LicensePlateKeyboard
                    value={carNum}
                    onChange={setCarNum}
                    onClose={() => setShowKeyboard(false)}
                />
            )}
        </View>
    )
}

export default connect(({cars}) => {
    return {
        ...cars
    }
})(AddStation)
